/**
 * 
 */
package com.gr.staffpm.pages.schedule;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.joda.time.DateTime;

import com.gr.staffpm.gof.observer.Subscribable;
import com.gr.staffpm.gof.observer.Subscriber;
import com.gr.staffpm.pages.schedule.model.MonthRow;

/**
 * @author Graham Rhodes 17 Mar 2011 22:07:00
 */
public class DayPanel extends Panel implements Subscribable {

    private static final long serialVersionUID = 1L;
    private final MonthRow row;
    private final int day;
    private final DateTime currentDate;
    private final List<Subscriber> subscribers = new ArrayList<Subscriber>();

    public DayPanel(String id, final int day, final MonthRow row, DateTime currentDate) {
        super(id);
        this.row = row;
        this.day = day;
        this.currentDate = currentDate;

        add(new AjaxLink<Void>("dayLink") {

            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {
                notifySubscribers(row.getDay(day), target);
            }

        }.add(new Label("dayNum", row.getDay(this.day).toString("dd"))));
    }

    @Override
    protected void onComponentTag(ComponentTag tag) {
        super.onComponentTag(tag);
        String cls = row.getDay(day).monthOfYear().equals(currentDate.monthOfYear()) ? "x-date-active" : "x-date-prevday";
        if ((new DateTime().getDayOfMonth() == row.getDay(this.day).getDayOfMonth())
                && (new DateTime().getMonthOfYear() == row.getDay(this.day).getMonthOfYear())
                && (new DateTime().getYear() == row.getDay(this.day).getYear()))
            cls += " x-date-today x-date-selected";
        tag.getAttributes().put("class", cls);
    }

    /* (non-Javadoc)
     * @see com.gr.staffpm.gof.observer.Subscribable#addSubscriber(com.gr.staffpm.gof.observer.Subscriber)
     */
    @Override
    public void addSubscriber(Subscriber subscriber) {
        subscribers.add(subscriber);
    }

    /* (non-Javadoc)
     * @see com.gr.staffpm.gof.observer.Subscribable#notifySubscribers(java.lang.Object, org.apache.wicket.ajax.AjaxRequestTarget)
     */
    @Override
    public void notifySubscribers(Object object, AjaxRequestTarget target) {
        for (Subscriber subscriber : subscribers)
            subscriber.notifySubscriber(object, target);
    }

}
